package list;

//class ListNode {
//    int val;
//    ListNode next;
//    ListNode(int x) {
//        val = x;
//        next = null;
//    }
//}

public class leetcode160 {

    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null){
            return null;
        }
        ListNode p1 = headA;
        ListNode p2 = headB;
        while(p1 != p2){
            if(p1.next == null){
                p1 = headB;
            }
            else{
                p1 = p1.next;
            }
            if(p2.next == null){
                p2 = headA;
            }
            else{
                p2 = p2.next;
            }
        }
        return p1;
    }

    private static ListNode createList(int[] vals, ListNode tail){
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;
        for(int val : vals){
            current.next = new ListNode(val);
            current = current.next;
        }
        current.next = tail;
        return dummy.next;
    }

    public static void main(String[] args) {
        int[] ListA = {4,1,8,4,5};
        int[] ListB = {5,6,1,8,4,5};
        int intersectVal = 8;

        ListNode commonTail = createList(new int[]{8, 4, 5}, null);
        ListNode headA = createList(new int[]{4, 1}, commonTail);
        ListNode headB = createList(new int[]{5, 6, 1}, commonTail);

        System.out.println("链表A:");
        printList(headA);
        System.out.println("链表B:");
        printList(headB);
        ListNode p = getIntersectionNode(headA, headB);
        System.out.println(p.val);
    }

    public static void printList(ListNode head) {
        while (head != null) {
            System.out.print(head.val + " -> ");
            head = head.next;
        }
        System.out.println("null");
    }
}

